import { onMounted, ref } from 'vue'
import { useRouter, onBeforeRouteUpdate } from 'vue-router'
import { getTabList, setTabList } from '@/composables/auth'
import { toast } from '@/composables/util'

export const useTagList = () => {
  const router = useRouter()

  const activeTab = ref(router.currentRoute.value.fullPath)

  const tabList = ref([
    {
      title: '后台首页',
      path: '/',
    },
  ])

  const addTabs = (tab) => {
    let noTab = tabList.value.findIndex((t) => t.path == tab.path) == -1

    if (noTab) {
      tabList.value.push(tab)
      setTabList(tabList.value)
    }
  }

  const init = () => {
    let tabs = getTabList()
    if (tabs) {
      tabList.value = tabs
    }
  }

  const tabChange = (e) => {
    router.push(e)
  }

  const removeTab = (targetName) => {
    if (tabList.value.length == 1) {
      toast('至少保留一个标签', 'error')
      return false
    }
    let tabs = tabList.value
    let showTab = activeTab.value
    if (showTab == targetName) {
      tabs.forEach((tab, index) => {
        if (tab.path == targetName) {
          let nextPage = tabs[index + 1] || tabs[index - 1]
          if (nextPage) {
            showTab = nextPage.path
          }
        }
      })
    }
    activeTab.value = showTab
    tabList.value = tabs.filter((tab) => tab.path != targetName)
    setTabList(tabList.value)
  }

  const changeCommand = (c) => {
    if (c == 'other') {
      tabList.value = tabList.value.filter(
        (tab) => tab.path == '/' || tab.path == activeTab.value
      )
    } else if (c == 'all') {
      tabList.value = [
        {
          title: '后台首页',
          path: '/',
        },
      ]
      activeTab.value = '/'
    }

    setTabList(tabList.value)
  }

  onBeforeRouteUpdate((to) => {
    activeTab.value = to.fullPath
    addTabs({ title: to.meta.title, path: to.fullPath })
  })

  onMounted(() => {
    init()
  })
  return {
    activeTab,
    tabList,
    addTabs,
    tabChange,
    removeTab,
    changeCommand,
  }
}
